package com.clwl.supervise.superviseapp.util.baiduAPI;


import com.baidu.aip.imageclassify.AipImageClassify;
import com.baidu.aip.ocr.AipOcr;
import com.baidu.aip.speech.AipSpeech;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;

@Component
public class BaiduAipUtil {

    private static Logger logger = LoggerFactory.getLogger(BaiduAipUtil.class);


    private static String fileUploadActive;


    private static String VOICE_APPID;


    private static String VOICE_KEY;


    private static String VOICE_SECRET;

    private static String TEXT_APPID;


    private static String TEXT_KEY;


    private static String TEXT_SECRET;


    private static String IMAGE_APPID;


    private static String IMAGE_KEY;


    private static String IMAGE_SECRET;


    public static void main(String[] args) {
        // 初始化一个AipSpeech
        AipSpeech client = new AipSpeech(VOICE_APPID, VOICE_KEY, VOICE_SECRET);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
        //client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
        //client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
        // System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

        // 调用接口
        JSONObject res = client.asr("test.pcm", "pcm", 16000, null);
        System.out.println(res.toString(2));

    }

    /**
     * 上传解析用的图片
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static String updateSpotImage(MultipartFile file) throws Exception {
        return FileUploadUtil.uploadTempImage(file).getFilePath();
    }

    /**
     * 删除解析用的图片
     *
     * @param path
     * @return
     * @throws IOException
     */
    public static void deleteSpotImage(String path) throws Exception {
        FileUploadUtil.deleteTempImage(path);
    }

    /**
     * 语音转文字
     *
     * @param filePath
     * @return
     */
    public static String getVoiceString(String filePath) {
        AipSpeech client = new AipSpeech(VOICE_APPID, VOICE_KEY, VOICE_SECRET);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
        // System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

        // 调用接口
        JSONObject res = client.asr(filePath, "wav", 16000, null);
        logger.info(res.toString());
        if (res.getInt("err_no") == 0 && "success.".equals(res.get("err_msg"))) {
            return res.getJSONArray("result").get(0) == null ? "" : res.getJSONArray("result").get(0).toString();
        } else {
            if ("request pv too much".equals(res.get("err_msg"))) {
                throw new RuntimeException("您的账号语音识别额度不足,无法完成识别任务！");
            } else {
                throw new RuntimeException("识别失败！" + res.get("err_msg"));
            }
        }
    }

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     *
     * @param fileDir 文件本地路径
     */
    public static JSONObject businessLicense(String fileDir) {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(TEXT_APPID, TEXT_KEY, TEXT_SECRET);
        HashMap<String, String> options = new HashMap<String, String>();
        // 参数为本地图片路径
        JSONObject res = client.businessLicense(fileDir, options);
        logger.info(res.toString());
        if (res.getInt("words_result_num") > 0) {
            return res.getJSONObject("words_result");
        } else {
            return null;
        }
    }

    /**
     * 识别文字
     *
     * @param fileDir
     * @return
     */
    public static JSONArray textSpot(String fileDir) {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(TEXT_APPID, TEXT_KEY, TEXT_SECRET);
        HashMap<String, String> options = new HashMap<String, String>();
        // 参数为本地图片路径
        JSONObject res = client.basicGeneral(fileDir, options);
        logger.info(res.toString());
        if (res.getInt("words_result_num") > 0) {
            return res.getJSONArray("words_result");
        } else {
            return null;
        }
    }

    /**
     * 二维码/条码识别
     *
     * @param fileDir
     * @return
     */
    public static JSONArray codeSpot(String fileDir) {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(TEXT_APPID, TEXT_KEY, TEXT_SECRET);
        HashMap<String, String> options = new HashMap<String, String>();
        // 参数为本地图片路径
        JSONObject res = client.qrcode(fileDir, options);
        logger.info(res.toString());
        if (res.getInt("codes_result_num") > 0) {
            return res.getJSONArray("codes_result");
        } else {
            return null;
        }
    }


    /**
     * 物品识别
     *
     * @param fileDir
     * @return
     */
    public static JSONArray materialSpot(String fileDir) {
        AipImageClassify client = new AipImageClassify(IMAGE_APPID, IMAGE_KEY, IMAGE_SECRET);
        HashMap<String, String> options = new HashMap<String, String>();
        // 参数为本地图片路径
        JSONObject res = client.advancedGeneral(fileDir, options);
        logger.info(res.toString());
        if (res.getInt("result_num") > 0) {

            return res.getJSONArray("result");
        } else {
            return null;
        }
    }


    @Value("${baidu.aip.voice.appid}")
    public void setVoiceAppid(String voiceAppid) {
        BaiduAipUtil.VOICE_APPID = voiceAppid;
    }

    @Value("${baidu.aip.voice.key}")
    public void setVoiceKey(String voiceKey) {
        BaiduAipUtil.VOICE_KEY = voiceKey;
    }

    @Value("${baidu.aip.voice.secret}")
    public void setVoiceSecret(String voiceSecret) {
        BaiduAipUtil.VOICE_SECRET = voiceSecret;
    }

    @Value("${baidu.aip.text.appid}")
    public void setTextAppid(String textAppid) {
        TEXT_APPID = textAppid;
    }

    @Value("${baidu.aip.text.key}")
    public void setTextKey(String textKey) {
        TEXT_KEY = textKey;
    }

    @Value("${baidu.aip.text.secret}")
    public void setTextSecret(String textSecret) {
        TEXT_SECRET = textSecret;
    }

    @Value("${baidu.aip.image.appid}")
    public void setImageAppid(String imageAppid) {
        IMAGE_APPID = imageAppid;
    }

    @Value("${baidu.aip.image.key}")
    public void setImageKey(String imageKey) {
        IMAGE_KEY = imageKey;
    }

    @Value("${baidu.aip.image.secret}")
    public void setImageSecret(String imageSecret) {
        IMAGE_SECRET = imageSecret;
    }

    @Value("${spring.profiles.file_upload_active}")
    public void setFileUploadActive(String fileUploadActive) {
        BaiduAipUtil.fileUploadActive = fileUploadActive;
    }

}
